
package com.scalar.chiptrack.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.scalar.ScalarException;
import com.scalar.chiptrack.db.DataSource;


public class Mailer {

    public static final String CONTENT_TYPE_TEXT = "text/plain";
    public static final String CONTENT_TYPE_HTML = "text/html";
    public static final String EMAIL_SEPARATOR = ",";
    
    private static Session s_session = null;
    
    /*static {
        Properties props = System.getProperties();
	props.put ("mail.smtp.host", ConfigManager.getMailHost());
        s_session = Session.getDefaultInstance (props, null);
    }*/
    
    public static void send (String from, String to, String subject, String message) throws Exception {
        send (from, to, null, null, subject, message, null, CONTENT_TYPE_HTML, true);
    }

    public static void send (String from, String to, String subject, String message, String contentType) throws Exception {
        send (from, to, null, null, subject, message, null, contentType, true);
    }
    
    public static void send (String from, String to, String cc, String bcc, String subject, String message, String[] fileAttachments) throws Exception {
        send (from, to, null, null, subject, message, fileAttachments, CONTENT_TYPE_HTML, true);
    }
    
    public static void send (String from, String to, String cc, String bcc, String subject, String message, String[] fileAttachments, String contentType) throws Exception {
        send (from, to, cc, bcc, subject, message, fileAttachments, contentType, true);
    }
    
    public static void send (String from, 
                             String to, 
                             String cc, 
                             String bcc, 
                             String subject, 
                             String message, 
                             String[] fileAttachments,
                             String contentType,
                             boolean qualifyEmail) throws Exception {
                                 
        if (ConfigManager.isMailerEnabled() == false) {
            return;
        }
        
        if ((to == null) || (to.trim().length() == 0)) {
            return;
        }
               
        to = getNotifiableEmails (to, qualifyEmail);
        cc = getNotifiableEmails (cc, qualifyEmail);
        bcc = getNotifiableEmails (bcc, qualifyEmail);
        Properties props = System.getProperties();
	    props.put ("mail.smtp.host", ConfigManager.getMailHost());
        s_session = Session.getDefaultInstance (props, null);
        MimeMessage msg = new MimeMessage (s_session);

        msg.setFrom (new InternetAddress (from));
	
        InternetAddress[] toAddress = InternetAddress.parse (to);
	msg.setRecipients (Message.RecipientType.TO, toAddress);
        
        if (cc != null) {
            InternetAddress[] ccAddress = InternetAddress.parse (cc);
            msg.setRecipients (Message.RecipientType.CC, ccAddress);
        }
        
        if (bcc != null) {
            InternetAddress[] bccAddress = InternetAddress.parse (bcc);
            msg.setRecipients (Message.RecipientType.BCC, bccAddress);
        }
        
        if  (subject != null) {
            msg.setSubject (subject);
        }
        
        // first part - message
        if (message == null) {
            message = "";
        }
        
        MimeBodyPart part1 = new MimeBodyPart();
	part1.setContent (message, contentType);

        // create the Multipart and its parts to it
	Multipart mp = new MimeMultipart();
        mp.addBodyPart (part1);
            
        // next parts - attachments
        int fileCnt = -1;
        if (fileAttachments != null) {
            fileCnt = fileAttachments.length;
        }
        
        
        MimeBodyPart part = null;
        FileDataSource fds = null;
        for (int i=0; i<fileCnt; i++) {
            part = new MimeBodyPart();
            
            // attach the file to the message
            fds = new FileDataSource (fileAttachments[i]);
            part.setDataHandler (new DataHandler (fds));
            part.setFileName (fds.getName());
            mp.addBodyPart (part);
        }
        
        // add the Multipart to the message
	msg.setContent(mp);

	// set the Date: header
	msg.setSentDate(new Date());
	    
	// send the message
	Transport.send(msg);
    }
    
    public static void main (String[] args) {
        try {
            String subject = "Maling from your a/c";
            
        
            String to = "lokesh.narayana@scalarsoft.com,chiptrac2@yahoo.com";
            to = getNotifiableEmails (to, true);
            String message = "sending it to " + to;
            System.out.println ("sending it to " + to);
            String[] attachments = new String[1];
            attachments[0] = "c:/asm/INT13.zip";
            //Mailer.send ("balaramputta@yahoo.com", 
              //           "balaram@scalarsoft.com", null, null,
                //         subject, message,
                  //       attachments/*, Mailer.CONTENT_TYPE_HTML*/);
                         
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
    
    /**
     * Returns user email IDs who opted to receive notifications 
     * and eliminates other emails
     */
    public static String getNotifiableEmails( String emails, boolean qualifyEmail ) throws ScalarException 
    {    
        Connection conn = null;
        PreparedStatement pstmt = null;
        StringBuffer resultEmails = new StringBuffer();
        String notifiableEmails = null;
        
        ResultSet rset = null;

        if (( emails == null ) || (emails.trim().length() == 0 )) {
            return notifiableEmails;
        }
        if (emails.endsWith( EMAIL_SEPARATOR ) == true ) {
            emails = emails.substring( 0, ( emails.length() - EMAIL_SEPARATOR.length() ));
        }
        
        if( qualifyEmail == false ) {
            return emails;
        }
        
        try {
            conn = DataSource.getConnection();
            StringBuffer query = new StringBuffer();
            String queryString = "";
            
            StringTokenizer st = new StringTokenizer (emails, EMAIL_SEPARATOR);
            while (st.hasMoreTokens()) {
                query.append ("'").append (st.nextToken()).append ("'").append (EMAIL_SEPARATOR);
            }
            queryString = query.toString();
            if (queryString.endsWith(EMAIL_SEPARATOR) == true) {
                queryString = queryString.substring(0, (queryString.length()-1));
            }
            
            queryString = SqlQueryMappings.get ("user.mail.getNotifiableEmails") + "(" + queryString + ")";
            //System.out.println ("query = " + queryString);
            
            pstmt = conn.prepareStatement (queryString);
            rset = pstmt.executeQuery();
            
            while (rset.next()) {
                
                resultEmails.append (rset.getString ("Email")).append (EMAIL_SEPARATOR);
            }
            
            notifiableEmails = resultEmails.toString();
            if (notifiableEmails.endsWith(EMAIL_SEPARATOR) == true) {
                notifiableEmails = notifiableEmails.substring(0, (notifiableEmails.length()-1));
            }
        }
        
        catch (Exception sqle) {
            sqle.printStackTrace();
            throw new ScalarException ("Exception while loading notifiable emails from database", sqle);
        }
        
        finally {
            if (rset != null) {
                try { rset.close(); } catch (SQLException ignore){}
            }
            if (pstmt != null) {
                try { pstmt.close(); } catch (SQLException ignore){}
            }
            if (conn != null) {
                try { conn.close(); } catch (SQLException ignore){}
            }
        }
        
        System.out.println (emails + " ==> Mailer.getNotifiableEmails() ==> " + notifiableEmails);
        return notifiableEmails;
        
    }
}